import {
	getUser
} from '@/api/user'
import {
	getCartNum
} from '@/api/store';
import {
	USER_INFO,
	TOKEN,
	CONFIG
} from '@/config/cachekey';
import Cache from '@/utils/cache'
import loginVue from '../../pages/login/login.vue';
const state = {
	config: Cache.get(CONFIG) || {
		center_setting: {},
		index_setting: {},
		navigation_menu: [],
		navigation_setting: {}
	},
	userInfo: {},
	market: {},
	token: Cache.get(TOKEN) || null,
	cartNum: "",
	postLikes: {}
};

const mutations = {
	LOGIN(state, opt) {
		state.token = opt.token.value;
		Cache.set(TOKEN, opt.token.value, opt.token.expire);
		wx.setStorage({
			key: 'isMarketer',
			data: JSON.stringify(opt.user.marketer),
			success(res) {
				// console.log('保存达人状态成功', res)
			}
		})
		state.userInfo = opt.user
	},
	LOGOUT(state) {
		state.token = undefined;
		state.userInfo = {}
		Cache.remove(TOKEN);
	},
	SETCARTNUM(state, num) {
		state.cartNum = num
	},
	SETUSERINFO(state, market) {
		state.market = market
	},
	UPDATEPOSTLIKES(state, posts) {
		if (Array.isArray(posts)) {
			const _postLikes = {}
			posts.forEach(item => {
				const {
					id,
					isLiked,
					like_num
				} = item
				_postLikes[item.id] = {
					isLiked,
					like_num
				}
			});
			state.postLikes = JSON.parse(JSON.stringify(Object.assign(state.postLikes, _postLikes)))
		}
	},
	SETCONFIG(state, data) {
		state.config = Object.assign(state.config, data)
		Cache.set(CONFIG, state.config);
	}
};

const actions = {
	getCartNum({
		state,
		commit
	}) {
		return new Promise(resolve => {
			if (!state.token) return uni.removeTabBarBadge({
				index: 2
			})
			getCartNum().then(res => {
				if (res.code == 1) {
					commit('SETCARTNUM', res.data.num)
					if (!res.data.num) return uni.removeTabBarBadge({
						index: 2
					})
					uni.setTabBarBadge({
						index: 2,
						text: String(res.data.num)
					})
					resolve()
				}
			})
		})
	},

	getUser({
		state,
		commit
	}) {
		return new Promise(resolve => {

			getUser().then(res => {
				if (res.s == 0) {
					commit('SETUSERINFO', res.d.market)
				}
				resolve()
			})
		})
	},
	setUser({
		state,
		commit
	}, opt) {
		commit('LOGIN', opt)
	}
};

export default {
	state,
	mutations,
	actions
};